import { Component, OnInit, Renderer2, ElementRef } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
import { VERSION as VERSION_ALAIN, TitleService } from '@delon/theme';
import { VERSION as VERSION_ZORRO, NzModalService } from 'ng-zorro-antd';
import { IdentityService } from '@shared/osharp/services/identity.service';

@Component({
  selector: 'app-root',
  template: `
    <router-outlet></router-outlet>
  `,
})
export class AppComponent implements OnInit {
  constructor(
    el: ElementRef,
    renderer: Renderer2,
    private router: Router,
    private titleSrv: TitleService,
    private modalSrv: NzModalService,
    private idSrv:IdentityService,
  ) {
    renderer.setAttribute(el.nativeElement, 'ng-alain-version', VERSION_ALAIN.full);
    renderer.setAttribute(el.nativeElement, 'ng-zorro-version', VERSION_ZORRO.full);
  }

  ngOnInit() {

    const access_token:string =   this.getUrlParam('access_token');
    const refresh_token:string =   this.getUrlParam('refresh_token');
    console.log('tokens:');
    console.log(access_token);
    console.log(refresh_token);
    if(access_token && refresh_token)
    {
      console.log("set tokens..");
      this.idSrv.setTmpToken(access_token,refresh_token);
    }

    this.router.events.pipe(filter(evt => evt instanceof NavigationEnd)).subscribe(() => {
      this.titleSrv.setTitle();
      this.modalSrv.closeAll();
    });
  }

  getUrlParam(name) { 
    const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); 
    const r = window.location.search.substr(1).match(reg); 
    if(r != null) return unescape(r[2]);
    return undefined; 
  }
}
